package com.weiyirong99.crm.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseActivity;
import com.weiyirong99.crm.app.bean.MyBean;
import com.weiyirong99.crm.app.server.MyJPushMessageReceiver;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * author  by  Canrom7 .
 * CreateDate 2021/8/30 11:46
 * Class LoginActivity
 */
public class LoginActivity extends BaseActivity implements OnClickListener {


    private View view;
    private ImageView userTv;
    private EditText etPhone;
    private EditText etPswd;
    private LinearLayout ll;
    private CheckBox loginCkb;
    private TextView tvCb;
    private TextView tvFw;
    private Button login;
    private boolean isLogin;
    private String phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isLogin = MMKV.defaultMMKV().decodeBool("isLogin");
        if (isLogin) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }
    }

    @Override
    public int getLayout() {
        return R.layout.activity_login;
    }


    @Override
    public void initView() {

        view = (View) findViewById(R.id.view);
        userTv = (ImageView) findViewById(R.id.user_tv);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etPswd = (EditText) findViewById(R.id.et_pswd);
        ll = (LinearLayout) findViewById(R.id.ll);
        loginCkb = (CheckBox) findViewById(R.id.login_ckb);
        tvCb = (TextView) findViewById(R.id.tv_cb);
        tvFw = (TextView) findViewById(R.id.tv_fw);
        login = (Button) findViewById(R.id.login);
        if (MMKV.defaultMMKV().decodeString("user") != null) {
            phone = MMKV.defaultMMKV().decodeString("user");
            etPhone.setText(phone);
        }

//        login.setOnClickListener(this);
        login.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {
//                String com = et_com.getText().toString();
//                if (TextUtils.isEmpty(com)) {
//                    ts("请填写公司账号");
//                    return;
//                }
                phone = etPhone.getText().toString();
//                String phone = "13120899583";
                if (TextUtils.isEmpty(phone)) {
                    ts("请填写账号");
                    return;
                }
                String pswd = etPswd.getText().toString();
//                String pswd = "888888";
                if (TextUtils.isEmpty(pswd)) {
                    ts("请填写密码");
                    return;
                }
                sendLogin(phone, pswd);
            }
        });


    }


    @Override
    public void initParms(Bundle parms) {

        setPermissions();
    }

    private void sendLogin(String user, String pswd) {
        MaterialDialog build = new MaterialDialog.Builder(getActivity())
                .content("正在登录...")
                .canceledOnTouchOutside(false)
                .progress(true, 100)
                .build();
        build.show();
        Log.e("WG", "sendLogin: " + MyJPushMessageReceiver.registrationID);
        String time = System.currentTimeMillis() / 1000 + "";
        Map<String, Object> jsonObj = new HashMap<>();
//        jsonObj.put("mobile", user);
        jsonObj.put("mobile", user);
        jsonObj.put("password", pswd);
//        jsonObj.put("password", pswd);
        jsonObj.put("registerId", MyJPushMessageReceiver.registrationID);
        JSONObject jsonObject = new JSONObject(jsonObj);

        OkGo.<String>post(Url.LoginUrl)
                .tag(LoginActivity.this)
                .upJson(jsonObject)
                .execute(new StringCallback() {

                    private String message;

                    @Override
                    public void onSuccess(Response<String> response) {
                        build.dismiss();
                        Log.e("WG", "onSuccess: " + response.body());

                        if (response.code() == 200) {
                            ts("登录成功");

                            MyBean myBean = new Gson().fromJson(response.body(), MyBean.class);
//                            Log.e("WG", "onSuccess: " + myBean.getToken());
//                            Log.e("WG", "onSuccess: " + myBean.getUser().getCompanyId());
//                            Log.e("WG", "onSuccess: " + myBean.getUser().getRole().getCompanyId());
                            MMKV.defaultMMKV().encode("token", myBean.getToken());
                            MMKV.defaultMMKV().encode("mobile", myBean.getUser().getMobile());
                            MMKV.defaultMMKV().encode("name", myBean.getUser().getName());
                            MMKV.defaultMMKV().encode("id", myBean.getUser().getId());
                            MMKV.defaultMMKV().encode("companyId", myBean.getUser().getCompanyId());
                            MMKV.defaultMMKV().encode("customerid", myBean.getUser().getRole().getCompanyId());
                            MMKV.defaultMMKV().encode("user", phone);
                            MMKV.defaultMMKV().encode("role", myBean.getUser().getRole().getName());
                            MMKV.defaultMMKV().encode("isLogin", true);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                message = jsonObject.getString("message");
                                Log.e("wg", "error: " + message);
                                ts(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");
                        build.dismiss();
                        ts(response.message());
                    }
                });
    }


    public static final String[] PERMISSIONS = {
            Permission.WRITE_EXTERNAL_STORAGE,
            Permission.READ_PHONE_STATE
            , Permission.CALL_PHONE
    };

    public void setPermissions() {
        XXPermissions.with(this)
                .permission(PERMISSIONS)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            ts("授权成功");
                        } else {
                            ts("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ts("被永久拒绝授权，请手动授予");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getActivity(), permissions);
                        } else {
                            ts("获取权限失败");
                        }
                    }
                });
    }


    @Override
    public BaseActivity getActivity() {
        return LoginActivity.this;
    }


    @Override
    public void onClick(View view) {

    }
}
